<template>
  <div class="add-or-edit-agent">
    <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm" label-position="top">
      <el-form-item label="座席名称:" prop="displayName">
        <el-input v-model.trim="form.displayName" :maxlength=10></el-input>
      </el-form-item>
      <el-form-item label="座席工号:" prop="exten">
        <el-input v-model.trim="form.exten" :maxlength=5 :minlength=4 auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码:" :prop="isAdd ? 'password' : ''">
        <el-input v-model.trim="form.password" type="password" autocomplete='new-password' readonly onfocus="this.removeAttribute('readonly')"></el-input>
        <div style="font-size: 12px;line-height: 15px;margin-bottom: 5px;">推荐密码前缀：{{randomPwd}}</div>
      </el-form-item>
      <el-row class="margin-t-15" style="margin-bottom: 15px">
        <span>工号类型：</span>
        <el-radio-group v-model="form.WorkersType" @change="changeWorkersType" :disabled="!isAdd">
          <el-radio label="generalType">普通工号</el-radio>
          <el-radio label="auxiliaryType">附属工号</el-radio>
        </el-radio-group>
      </el-row>
      <el-row v-if="!isAuxiliaryType && isAdd" style="margin-bottom: 15px">
        <span>是否为管理员：</span>
        <el-radio-group v-model="form.type">
          <el-radio label="agent">否</el-radio>
          <el-radio label="manager">是</el-radio>
        </el-radio-group>
      </el-row>
      <el-form-item label="继承:" prop="inheritedFrom" v-if="isAuxiliaryType" class="margin-t-15">
        <el-select v-model="form.inheritedFrom"
                   filterable
                   clearable
                   size="mini"
                   collapse-tags
                   @change="changeAgent"
                   @visible-change="isRenderAgentsOne"
                   :placeholder="$t('report.pleChoseAgent')">
          <el-option
            v-for="item in agentOptions1"
            :label="item.label"
            :value="item.id"
            :key="item.id">
          </el-option></el-select>
      </el-form-item>
      <el-form-item label="手机:" prop="mobile">
        <el-input v-model.trim="form.mobile" :disabled="isAuxiliaryType"></el-input>
      </el-form-item>
      <el-form-item label="邮箱:">
        <el-input v-model.trim="form.email"></el-input>
      </el-form-item>
      <el-form-item label="外显号码:" v-if="!isAuxiliaryType && flag !== 'ecommerce'">
        <el-input v-model.trim="form.callerIDNum"></el-input>
      </el-form-item>
      <el-form-item label="后处理时长:" v-if="!isAuxiliaryType && flag !== 'ecommerce'">
        <el-input v-model.trim="form.AutoBusyTime"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="addRole" v-if="isAdd">
        <el-select v-model="form.addRole" placeholder="请选择角色">
          <el-option
            v-for="item in roles"
            :key="item._id"
            :label="item.display_name"
            :value="item._id">

          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="版本" prop="uversion">
        <el-select v-model="form.uversion" placeholder="请选择版本" :disabled="isAuxiliaryType">
          <el-option
            v-for="item in licenceType"
            :key="item.code_value"
            :label="item.code_name"
            :value="item.code_value">

          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  import {checkform} from '@/utils/validate'
  import * as m7Utils from '@/utils/m7Utils'
  import md5 from 'md5'
  export default {
    name: 'addOrEditAgent',
    data () {
      let validateNum = (rule, value, callback) => {
        let message = checkform(value, 'Number3')
        if (message) {
          callback(new Error(this.$t(message)))
        } else {
          if (value < 1000) {
            callback(new Error('起始工号最少4位'))
          } else {
            callback()
          }
        }
      }
      let validateNumber = (rule, value, callback) => {
        let message = checkform(value, 'Number3')
        if (message) {
          callback(new Error(this.$t(message)))
        } else {
          callback()
        }
      }
      return {
        flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf', // 是否是电商版
        agentOptions: [],
        agentOptions1: [], // 点击座席得时候开始渲染存值
        boolNum1: 1, // 点击座席得时候开始渲染计数
        isAdd: true,
        isAuxiliaryType: false, // 是否是附属工号
        randomPwd: '', // 推荐密码
        rules: {
          password: { required: true, message: '请输入密码', trigger: 'blur' },
          addRole: { required: true, message: '请选择角色', trigger: 'blur' },
          uversion: { required: true, message: '请选择版本', trigger: 'blur' },
          AutoBusyTime: {validator: validateNumber, trigger: 'blur'},
          mobile: {validator: validateNumber, trigger: 'blur'},
          displayName: { required: true, message: '请输入座席名称', trigger: 'blur' },
          exten: [{ required: true, message: '请输入工号', trigger: 'blur' }, {validator: validateNum, trigger: 'blur'}]
        },
        currPbxstatus: {
          title: '',
          type: ''
        }, // 当前pbx的状态
        form: {
          inheritedFrom: '',
          uversion: '',
          addRole: '',
          AutoBusyTime: '',
          callerIDNum: '',
          email: '',
          type: 'agent',
          mobile: '',
          password: '',
          WorkersType: 'generalType',
          displayName: '',
          exten: ''
        }
      }
    },
    components: {
    },
    watch: {
    },
    props: {
      licenceType: Array,
      roles: Array
    },
    computed: {
      pbx () {
        return this.$store.state.config.callCenter.currentPBX
      }
    },
    methods: {
      saveAddAgents () {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            let _data = {}
            if (this.form.type === 'manager' && this.form.WorkersType !== 'auxiliaryType' && this.isAdd) {
              let managerID = null
              for (var i = 0; i < this.roles.length; i++) {
                if (this.roles[i].display_name === '管理员') {
                  managerID = this.roles[i]._id
                }
              }
              if (managerID != null) {
                _data.role = [managerID]
              }
            }
            if (this.form.exten.length === 4 && (this.form.exten.substr(0, 1) === '0' || this.form.exten.substr(0, 1) === '9')) {
              this.$message.error('座席工号为4位数不能以数字0、9开头')
              return
            } else if (this.form.exten.length === 5 && (this.form.exten.substr(0, 1) === '0' || this.form.exten.substr(0, 1) === '9' || this.form.exten.substr(0, 1) === '1')) {
              this.$message.error('座席工号为5位数不能以数字0、1、9开头')
              return
            }
            if (this.form.email !== '') {
              if (checkform(this.form.email, 'Email')) {
                this.$message.error('邮箱格式错误！')
                return
              }
            }
            if (this.form.WorkersType === 'auxiliaryType' && this.form.inheritedFrom === '') {
              this.$message.error(this.$t('report.pleChoseAgent'))
              return
            }
            if (this.form.WorkersType === 'auxiliaryType' && this.form.inheritedFrom !== '') {
              _data.inheritedFrom = this.form.inheritedFrom
            }
            _data.salt = ''
            const array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
            for (let i = 0; i < 6; i++) {
              _data.salt += array[Math.floor(Math.random() * 25)]
            }
            // 密码校验
            let passwordNew = this.form.password
            if (passwordNew !== null && passwordNew !== '') {
              let regexPass = false
              let lengthRegex = new RegExp('^.{8,}$') // >= 8位
              let characterRegex = new RegExp('[a-z]') // 小寫
              let characterRegex2 = new RegExp('[A-Z]') // 大寫
              let numberRegex = new RegExp('[0-9]')// 數字
              let chinese = new RegExp('[\\u4E00-\\u9FFF]+', 'g') // 是否有中文
              let num = 0
              let temporary = this.form.password
              temporary = temporary.replace(/[^0-9a-zA-Z]/g, '')
              if (characterRegex.test(passwordNew)) {
                num += 1
              }
              if (characterRegex2.test(passwordNew)) {
                num += 1
              }
              if (numberRegex.test(passwordNew)) {
                num += 1
              }
              if ((passwordNew.length - temporary.length) > 0) {
                num += 1
              }
              if (num >= 3) {
                regexPass = true
              } else {
                regexPass = false
              }
              if (!lengthRegex.test(passwordNew)) {
                regexPass = false
              }
              if (chinese.test(passwordNew)) {
                regexPass = false
              }
              let limitArr = ['%', '&', '"', '\'', '<', '>', '+', '=']
              for (let i = 0; i < limitArr.length; i++) {
                if (passwordNew.indexOf(limitArr[i]) > -1) {
                  regexPass = false
                  break
                }
              }
              if (!regexPass) {
                this.$message.error(this.$t('config.agent.newPasswordRule'))
                return
              }
            }
            if (passwordNew !== '') {
              // 去除敏感字段名 值进行base64加壳
              _data.sosdwarp = m7Utils.Base64.encode(passwordNew)
              _data.hexPassword = md5(passwordNew + _data.salt)
            }
            if (this.currPbxstatus && this.currPbxstatus.type === 'inverse' && this.isAdd) {
              this.$confirm('前pbx实例已饱和，建议不要再往该pbx上继续添加座席，具体详情请联系运维leader进行咨询', this.$t('public.tip'), {
                confirmButtonText: '继续添加',
                cancelButtonText: this.$t('public.cancel'),
                cancelButtonClass: 'primary_btn',
                confirmButtonClass: 'primary_btn',
                type: 'warning'
              }).then(() => {
                this.handleAddOrEdit(_data)
              })
            } else {
              this.handleAddOrEdit(_data)
            }
          }
        })
      },
      handleAddOrEdit (_data) {
        _data.displayName = this.form.displayName
        _data.exten = this.form.exten
        _data.type = this.form.type
        _data.mobile = this.form.mobile
        _data.email = this.form.email
        _data.callerIDNum = this.form.callerIDNum
        _data.AutoBusyTime = this.form.AutoBusyTime
        _data.uversion = this.form.uversion
        _data.Account = this.$store.state.session.account.account
        _data.PBX = this.pbx
        if (this.isAdd) {
          _data.addRole = this.form.addRole
          _data.status = 'enable'
          _data.action = 'add'
          this.saveDispatch(_data, '添加成功！')
        } else {
          _data.action = 'update'
          _data.status = this.form.status
          _data._id = this.form._id
          this.saveDispatch(_data, '修改成功！')
        }
      },
      saveDispatch (data, flag) {
        console.log(data)
        this.$store.dispatch('updateAgent', data).then((res) => {
          if (res.success) {
            this.$message.success(flag)
            this.$emit('addAgentSuccess')
          } else {
            if (res && res.repeatList && res.repeatList.length !== 0 && res.repeatList[0] === 'callerIDNum') {
              this.$message.error(`该外显号已被${res.agentInfo}绑定，请检查！`)
            } else if (res && res.repeatList && res.repeatList.length !== 0 && res.repeatList[0] === 'exten') {
              this.$message.error('座席工号重复！')
            } else if (res && res.repeatList && res.repeatList.length !== 0 && res.repeatList[0] === 'mobile') {
              this.$message.error(`该号码已被${res.agentInfo}绑定，请检查您的号码`)
            } else if (res && res.repeatList && res.repeatList.length !== 0 && res.repeatList[0] === 'email') {
              this.$message.error(`该邮箱已被${res.agentInfo}绑定，请检查您的邮箱`)
            } else if (res && res.repeatList && res.repeatList.length !== 0 && res.repeatList[0] === 'name') {
              this.$message.error('座席名称重复！')
            }
          }
        })
      },
      changeAgent (val) {
        console.log(val)
        for (let i = 0; i < this.agentOptions.length; i++) {
          if (this.agentOptions[i].id === val) {
            this.form.mobile = this.agentOptions[i].mobile
            this.form.uversion = this.agentOptions[i].uversion
          }
        }
      },
      // 点击座席下拉组件开始渲染座席组件(避免首次加载较慢)
      isRenderAgentsOne (bool) {
        console.log(bool)
        this.agentOptions1 = this.agentOptions
//        if ((this.boolNum1 < 2) && bool) {
//          this.agentOptions1 = this.agentOptions
//          this.boolNum1 += 1
//        }
      },
      changeWorkersType (val) {
        this.form.mobile = ''
        if (this.form.WorkersType === 'auxiliaryType') {
          this.isAuxiliaryType = true
          this.form.inheritedFrom = ''
        } else {
          this.isAuxiliaryType = false
        }
      },
      initAgent (data, isAdd, currPbxState) {
        this.currPbxstatus = currPbxState
        this.form = m7Utils.deepClone(data)
        let _agent = []
        if (this.$store.state.session.ivrMap[this.pbx] && this.$store.state.session.ivrMap[this.pbx].data) {
          _agent = this.$store.state.session.ivrMap[this.pbx].data.account_user
          this.agentOptions = []
          for (let i = 0; i < _agent.length; i++) {
            if (!(_agent[i].inheritedFrom !== '') && _agent[i].status === 'enable') {
              this.agentOptions.push({ label: `${_agent[i].displayName}[${_agent[i].exten}]`, value: _agent[i].exten, id: _agent[i]._id, deptId: _agent[i].deptId ? _agent[i].deptId : '', mobile: _agent[i].mobile ? _agent[i].mobile : '', uversion: _agent[i].uversion ? _agent[i].uversion : '' })
            }
          }
        }
        this.$nextTick(function () {
          this.$refs['form'].clearValidate()
        })
        if (isAdd) {
          this.isAdd = true
          this.isAuxiliaryType = false
        } else {
          this.isRenderAgentsOne(true)
          this.isAdd = false
          if (data.WorkersType === 'auxiliaryType') {
            this.isAuxiliaryType = true
          } else {
            this.isAuxiliaryType = false
          }
        }
      },
      randomWord (min, max) {
        let str = ''
        let range = min
        let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
        // 随机产生
        range = Math.round(Math.random() * (max - min)) + min
        for (let i = 0; i < range; i++) {
          let pos = Math.round(Math.random() * (arr.length - 1))
          str += arr[pos]
        }
        return str
      },
      updatePwd () {
        let _pattern = '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$'
        let _pwd = this.randomWord(8, 11)
        while (!_pwd.match(_pattern)) {
          _pwd = this.randomWord(8, 11)
        }
        let teStr = '#_!'
        let _numRan = Math.floor(Math.random() * 4)
        let _arrayStr = _pwd.split('')
        _arrayStr.splice(_numRan, 0, teStr.charAt(_numRan))
        this.randomPwd = _arrayStr.join('')
      }
    },
    beforeMount () {
//      this.$store.dispatch('checkPbxLoadInfo', {'pbxId': this.pbx}).then((state) => {
//        this.currPbxstatus = state
//      })
//      this.$store.dispatch('getCache', { type: 'agents' }).then(agents => {
//        console.log(agents)
//        agents.map(agent => {
//          if (!(agent.inheritedFrom !== '')) {
//            this.agentOptions.push({ label: `${agent.displayName}[${agent.exten}]`, value: agent.exten, id: agent._id, deptId: agent.deptId ? agent.deptId : '', mobile: agent.mobile ? agent.mobile : '', uversion: agent.uversion ? agent.uversion : '' })
//          }
//        })
//      })
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .margin-t-15
    margin-top 15px
  .add-or-edit-agent
    margin 20px
    overflow-y hidden
    display: flex;
    -ms-flex-direction: column;
    flex-direction: column;
    overflow-y: auto;
    font-size: 12px;
    .margin-l-10
      margin-left 10px
    .pag-wapper
      position: absolute;
      right: 15px;
      top: 14px;
    .main-color
      color $c-main
      cursor pointer
    .wapper
      display flex
      flex-direction column
    .tool
      position relative
      border 1px solid #e7e7eb
      border-bottom 0
      padding  12px 15px
      /*display flex*/
      justify-content space-between
    .primary_btn
      padding 0px 10px
      min-width 60px
    .pink
      color $c-pink
      cursor pointer
    .prompt
      color $c-prompt
</style>

